<?php
class ProductsAction extends AdminPublicAction{

/*======================================================================
	信息列表
======================================================================================*/
	public function index(){
		
		if((isset($_GET['sort'] ) && !empty($_GET['sort'])) && (isset($_GET['updown'] ) && !empty($_GET['updown']))){
			 $sort   = I('sort');
			 $upDown = I('updown');
		}else{
			 $_GET['sort'] = $sort = "sort_order";
			 $_GET['updown'] = $upDown = "desc";
			
		}
		import('Class.Category', APP_PATH);
		$cate = Category::tep_get_category_tree();
		
		$keyword = I('keyword','');
		$category = I('category','');
		$status = I('status',-1);
		$products_type = I('products_type',-1);
		
		//關鍵字查詢
		if(tep_not_null($keyword)){
			$where['products_name']  = array('like','%'.$keyword.'%');
			$where['products_description']  = array('like','%'.$keyword.'%');
			$where['_logic'] = 'or';
			$map['_complex'] = $where;
		}
		//省份城市筛选
		$map = get_map_city_id($map);
		//var_dump($map);die;
		$this->citycode = $map['citycode'];
		$this->provcode = $map['provcode'];
		$this->area_id = $map['area_id'];
		//篩選分類
		if(tep_not_null($category))
		{
			$cateStr  = '';
			$ptc = M('products_to_categories')->where(array('categories_id' => $category))->select();
			foreach($ptc as $v ){
				$cateStr .= $v['products_id'].',';	
			}
			$map['products_id'] =  array('in',substr($cateStr,0,-1));
		}
		
		//篩選狀態
		if($status >= 0 ) $map['products_status'] = $status;
		if($products_type >= 0 ) $map['products_type'] = $products_type;
		
		//$map['language_id'] = (int)L('lan_id');
		
		import("ORG.Util.Page");
		$page = 10;		
		$count = D('ProductsView')->where($map)->count();	
		$Page = new Page($count, $page);	
		$infoList = D('ProductsView')->getAll($map,$Page->firstRow. ',' . $Page->listRows,$sort.' '.$upDown);	
		//var_dump($infoList);die;
		if (S("success") != "")
			{
				$this->assign("msg", '<div class="success">'.S("success").'</div>');
				S('success',NULL);
			}
			
			if (S("err") != "")
			{
				$this->assign("msg", '<div class="err">'.S("err").'</div>');
				S('err',NULL);
			}

		$this->category = $category;
		$this->status = $status;
		$this->products_type = $products_type;
		$this->keyword = $keyword;
		$this->cate = $cate;	
		$this->page = $Page->show();	
		$this->infoList = $infoList;
		$this->li1 = 'current';
		$this->left_product = 'current';
		$this->display();
	}
/*======================================================================
	添加信息 & 編輯信息
======================================================================================*/
	public function detail(){
		

			import('Class.Category', APP_PATH);
			//================ 語言分類切換  Tab === //
			/* $langList = explode(",", C('LANG_LIST'));
			$lang = array();
			foreach($langList as $item)
			{
				$langTxt = '';
				if ($item == 'tchinese') $langTxt = '繁體';
				if ($item == 'schinese') $langTxt = '简体';
				if ($item == 'english')  $langTxt = 'English';
				$lang[] = array("value" => $item, 'txt'=> $langTxt );			
			}			 */
			//================ 語言分類切換  Tab === //
			$id = I('id','',intval);
			//================ 判斷是編輯還是添加 ===================== //
			if(tep_not_null($id) > 0 && is_numeric($id)){
				$categories = M('products_to_categories')->where(array('products_id' => $id))->select();
				$infoList = D('ProductsView')->getOne(array('p.products_id' => $id));				
				$BigImg = M('products_images')->where(array('products_id' => $id))->order('sort_order')->select();	

				
				if ( isset($infoList["products_image"]) && $infoList["products_image"] != '')
				{
					$imageShow = '<input type="hidden"  name="del_iamge" value="flase" />
								  <div id="image">
								    <a  href="'.__ROOT__.'/Public/images/products/thumb/m_'.$infoList["products_image"].'" class="fancyBox"><img src="'.__ROOT__.'/Public/images/products/thumb/m_'.$infoList["products_image"].'" width="200"></a><br />
									<a  href="#" onclick="delImages();return false;"  class="del">Delete</a></div>';
				}
				
				$this->BigImg  =$BigImg;
				$this->categories = $categories;
				$this->infoList = $infoList;
				$this->imageShow = $imageShow;
				$this->action = 'editHandle';
				$this->actionName = 'Save';
			}else{
				$categories = array();
				$this->action = 'addHandle';
				$this->actionName = 'add';	
			}
			//================ 判斷是編輯還是添加 ===================== //
			//================ 產品分類 ===================== //
			$cate_list = D('CategoryRelation')->relation(true)->order('sort_order', 'ASC')->select();
			$cateArr = array();
			
			foreach($cate_list as $v){
				foreach($categories as $c){
					if($c['categories_id'] == $v['categories_id']){
						$checked = 1;
						break;
					}else{
						$checked = 0;	
					}
				}
				$v['checked'] = $checked;
				$v['child'] = M('categories')->where(array('parent_id' => $v['categories_id']))->count();	
				$cateArr[] = $v;
			}
			$cate = Category::get_products_to_category_tree($cateArr);
			//================ 產品分類 ===================== //
			$this->cate = $cate;
			$this->getcity();
			$this->left_product = 'current';
			
			$this->display();
					
		}
/*======================================================================
	添加信息處理
======================================================================================*/
	public function addHandle(){
		 
		if(IS_POST){
			$data['products_name'] = I('post.products_name');
			$data['products_description'] = I('post.products_description');
			$data['products_oldprice'] = I('post.products_oldprice');
			$data['products_type'] = I('post.products_type');
			$data['products_paimai_price'] = I('post.products_paimai_price');
			$data['products_date_avaliable'] = I('post.products_date_avaliable');
			$data['provcode'] = I('post.provcode');
			$data['citycode'] = I('post.citycode');
			$data['area_id'] = I('post.area_id');
			$data['contact_person'] = I('post.contact_person');
			$data['contact_tel'] = I('post.contact_tel');
			$data['contact_qq'] = I('post.contact_qq');
			$data['contact_wechat'] = I('post.contact_wechat');
			$data['contact_address'] = I('post.contact_address');
			$data['up_flag'] = I('post.up_flag');
			$data['jiaji_flag'] = I('post.jiaji_flag');
			$data['recommend'] = I('post.recommend');
			$data['show_flag'] = I('post.show_flag');
			$data['products_close'] = I('post.products_close');
			if($data['products_close']){
				$data['close_reason'] = I('post.close_reason');
			}
			$data['member_id'] = I('post.member_id');
			
			$data['products_quantity'] = I('post.products_quantity');
			$data['products_model'] = I('post.products_model');
			$data['products_price'] = I('post.products_price');
			$data['products_date_added'] =  I('post.products_date_added',date("Y-m-d H:i:s"));
			$data['products_weight'] = I('post.products_weight');
			$data['products_status'] = I('post.products_status',0,'intval');
			$data['sort_order'] = I('post.sort_order');
			$products = M("products");
			$insertId = $products->add($data);	
			
			$cateArr = I('post.categories_id');	
			foreach($cateArr as $v){
				$map['products_id']  = $insertId;	 
				$map['categories_id'] = $v;
				M('products_to_categories')->add($map);
			}
			
			$files = I('post.file');
			$htmlcontent = I('post.htmlcontent');
			foreach($files as $k => $v){
				$picMap['products_id'] = $insertId;
				$picMap['image'] = $v;	
				$picMap['sort_order'] = $k;	
				$picMap['htmlcontent'] = $htmlcontent[$k];	
				M("products_images")->add($picMap);
			}
				
			if ($_FILES['products_image']['error'] == 0)
			{
				//上传图片
				import('@.ORG.UploadFile');
				$upload = new UploadFile('products_image');
					//设置上传文件大小 
				$upload->maxSize            = 6000000;
					//设置上传文件类型
				$upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
					//设置附件上传目录
				$upload->savePath 			=  './Public/images/products/';
					//设置需要生成缩略图，仅对图像文件有效
				$upload->thumb              = true;
					// 縮略圖路徑
				$upload->thumbPath         =  './Public/images/products/thumb/';
				// 设置引用图片类库包路径
				$upload->imageClassPath     = '@.ORG.Image';
					//设置需要生成缩略图的文件后缀
				$upload->thumbPrefix        = 'm_,s_';  //m_大缩略图，s_小缩略图
					//设置缩略图最大宽度
				$upload->thumbMaxWidth      = '300,100';
					//设置缩略图最大高度
				$upload->thumbMaxHeight     = '300,100';
					//设置上传文件规则
				$upload->saveRule           = 'uniqid';
				if(!$upload->upload()) 
				{			
					S('err','image save failed! '.$upload->getErrorMsg());				
					$this->redirect('index');
				}
				else
				{
					$info =  $upload->getUploadFileInfo();
					$data['products_image'] = $info[0]['savename'];
					$products = M("products");
					$products->where(array("products_id" =>$insertId))->save($data);
					S('success','Products successfully added!');			
					$this->redirect('index');					
				}
			}else{
					S('success','Products successfully added!');			
					$this->redirect('index');			
			}
		}else{
			$this->redirect('index');
		}				
		
	}

/*======================================================================
	編輯信息處理
======================================================================================*/
	public function editHandle(){
		if(IS_POST){
			$pid = I('post.products_id') ;
			$data['products_id'] = $pid;
			$data['products_name'] = I('post.products_name');
			$data['products_description'] = I('post.products_description');
			$data['products_oldprice'] = I('post.products_oldprice');
			$data['products_type'] = I('post.products_type');
			$data['products_paimai_price'] = I('post.products_paimai_price');
			$data['products_date_avaliable'] = I('post.products_date_avaliable');
			$data['provcode'] = I('post.provcode');
			$data['citycode'] = I('post.citycode');
			$data['area_id'] = I('post.area_id');
			$data['contact_person'] = I('post.contact_person');
			$data['contact_tel'] = I('post.contact_tel');
			$data['contact_qq'] = I('post.contact_qq');
			$data['contact_wechat'] = I('post.contact_wechat');
			$data['contact_address'] = I('post.contact_address');
			$data['up_flag'] = I('post.up_flag');
			$data['jiaji_flag'] = I('post.jiaji_flag');
			$data['recommend'] = I('post.recommend');
			$data['show_flag'] = I('post.show_flag');
			$data['products_close'] = I('post.products_close');
			if($data['products_close']){
				$data['close_reason'] = I('post.close_reason');
			}
			$data['member_id'] = I('post.member_id');
			
			$data['products_quantity'] = I('post.products_quantity');
			$data['products_model'] = I('post.products_model');
			$data['products_price'] = I('post.products_price');
			$data['products_last_modified'] =  date("Y-m-d H:i:s");
			$data['products_weight'] = I('post.products_weight');
			$data['products_status'] = I('post.products_status',0,'intval');
			$data['sort_order'] = I('post.sort_order');
			M("products")->save($data);	
			
			M('products_to_categories')->where(array('products_id' => $pid))->delete();
			$cateArr = I('post.categories_id');	
			foreach($cateArr as $v){
				$cateMap['products_id']  = $pid;	 
				$cateMap['categories_id'] = $v;
				M('products_to_categories')->add($cateMap);
			}
			
			$files = I('post.file');
			
			$htmlcontent = I('post.htmlcontent');
			foreach($files as $k => $v){
				$picMap['products_id'] = $pid;
				$picMap['image'] = $v;	
				$picMap['sort_order'] = $k;	
				$picMap['htmlcontent'] = $htmlcontent[$k];	
				M("products_images")->add($picMap);
			}
			$imgcontent = I('post.imgcontent');
			$img_sort = I('post.img_sort');
			
			foreach ($img_sort as $k => $v) {
				M("products_images")->where(array('id'=>$v))->setField('sort_order',$k);
			}
			foreach ($imgcontent as $key => $value) {
				M("products_images")->where(array('id'=>$key))->setField('htmlcontent',$value);
			}
			
			
			if ($_FILES['products_image']['error'] == 0)
			{
				//上传图片
				import('@.ORG.UploadFile');
				$upload = new UploadFile('products_image');
					//设置上传文件大小 
				$upload->maxSize            = 6000000;
					//设置上传文件类型
				$upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
					//设置附件上传目录
				$upload->savePath 			=  './Public/images/products/';
					//设置需要生成缩略图，仅对图像文件有效
				$upload->thumb              = true;
					// 縮略圖路徑
				$upload->thumbPath         =  './Public/images/products/thumb/';
				// 设置引用图片类库包路径
				$upload->imageClassPath     = '@.ORG.Image';
					//设置需要生成缩略图的文件后缀
				$upload->thumbPrefix        = 'm_,s_';  //m_大缩略图，s_小缩略图
					//设置缩略图最大宽度
				$upload->thumbMaxWidth      = '300,100';
					//设置缩略图最大高度
				$upload->thumbMaxHeight     = '300,100';
					//设置上传文件规则
				$upload->saveRule           = 'uniqid';
				if(!$upload->upload()) 
				{			
					S('err','image save failed! '.$upload->getErrorMsg());
					$this->redirect('index');
				}
				else
				{
					$image = M("products")->where(array("products_id" => $id))->getField('products_image');
					@unlink("./Public/images/products/".$image);
					@unlink("./Public/images/products/thumb/s_".$image);
					@unlink("./Public/images/products/thumb/m_".$image);
					$info =  $upload->getUploadFileInfo();
					M("products")->where(array("products_id" => $pid))->setField('products_image',$info[0]['savename']);	
			
				}
			}
			else
			{
				if (isset($_POST['del_iamge']) && $_POST['del_iamge'] == 'true')
				{
					$image = M("products")->where(array("products_id" => $pid))->getField('products_image');
					@unlink("./Public/images/products/".$image);
					@unlink("./Public/images/products/thumb/s_".$image);
					@unlink("./Public/images/products/thumb/m_".$image);
					M("products")->where(array('products_id' => $id))->setField('products_image','');
				}
			}	
			S('success','Products update successfully!');
			$this->redirect('index');
		}else{
			$this->redirect('index');	
		}
	}
/*======================================================================
	信息刪除
======================================================================================*/
	public function deleteProduct(){
		$id = I('id');
		if(tep_not_null($id) && is_numeric($id)){	
			$image = M("products")->where(array("products_id" => $id))->getField('products_image');
			@unlink("./Public/images/products/".$image);
			@unlink("./Public/images/products/thumb/s_".$image);
			@unlink("./Public/images/products/thumb/m_".$image);
			$file = M('products_images')->where(array('products_id'=> $id))->select();
			foreach($file as $v){
				@unlink("./Public/images/products/".$v['image']);
				@unlink("./Public/images/products/thumb/s_".$v['image']);
				@unlink("./Public/images/products/thumb/m_".$v['image']);
			}
			M('products')->where(array('products_id' => $id))->delete();
			M('products_images')->where(array('products_id' => $id))->delete();
			M('products_to_categories')->where(array('products_id' => $id))->delete();
			S('success','Products deleted successfully!');
			$this->redirect('index');
		}else{
			S('err','Products deleted failure!');
			$this->redirect('index');
			}
		
		
	}	
/*======================================================================
	信息顯示
======================================================================================*/
	public function changeStatus(){	
			$check = M("products")->where(array("products_id" => (int)$_GET['id']))->getField('products_status');	
			$products_status = ($check == 1)?0:1;		
			M("products")->where(array("products_id" => (int)$_GET['id']))->setField('products_status',$products_status);
			echo (int)$products_status;		
			
	}
/*======================================================================
	刪除批量上傳的圖片
======================================================================================*/
	public function removeImg(){
		$file = $_GET['file'];
        @unlink("./Public/images/products/".$file);
		@unlink("./Public/images/products/thumb/m_".$file);
		@unlink("./Public/images/products/thumb/s_".$file);
	}
/*======================================================================
	刪除批量已保存到數據庫的圖片和數據
======================================================================================*/
	public function removePic(){
		$id = $_GET['id'];
		$file = M('products_images')->where(array('id'=> $id))->getField('image');
        @unlink("./Public/images/products/".$file);
		@unlink("./Public/images/products/thumb/m_".$file);
		@unlink("./Public/images/products/thumb/s_".$file);
		M('products_images')->where(array('id'=> $id))->delete();
	}

}

?>
